我想在编译时启用/禁用分支,具体取决于是否可以使用某些参数调用函数。
在if constexpr
条件下需要做什么?
我可以通过std::result_of(decltype(add)(A, B))
获取结果类型,但是如何检查结果类型是否有效? (即如何将此信息转换为bool
?)
const auto add = [](const auto a, const auto b) { return a + b; };
const auto subtract = [](const auto a, const auto b) { return a - b; };
template <typename A, typename B>
void foo(A a, B b) {
if constexpr ( /* can add(a, b) be called? */ ) {
std::cout << "result of add: " << add(a, b) << std::endl;
}
if constexpr ( /* can subtract(a, b) be called? */ ) {
std::cout << "result of subtract: " << subtract(a, b) << std::endl;
}
}
答案 0 :(得分:4)
首先,你需要让你的lambda SFINAE友好。
#define RETURNS(...)\
noexcept(noexcept(__VA_ARGS__))\
->decltype(__VA_ARGS__)\
{ return __VA_ARGS__; }
const auto add = [](const auto a, const auto b) RETURNS( a + b );
const auto subtract = [](const auto a, const auto b) RETURNS( a - b );
现在可以在SFINAE环境中测试加法和减法。
namespace details {
template<class, class, class...>
struct can_invoke:std::false_type {};
template<class F, class...Args>
struct can_invoke<F, std::void_t< std::result_of_t< F&&(Args&&...) > >, Args... >:
std::true_type
{};
}
template<class F, class...Args>
using can_invoke_t = details::can_invoke<F, Args...>;
template<class F, class...Args>
constexpr can_invoke_t< F, Args... >
can_invoke( F&&, Args&&... ){ return {}; }
我们准备好了:
template <typename A, typename B>
void foo(A a, B b) {
if constexpr ( can_invoke( add, a, b ) ) {
std::cout << "result of add: " << add(a, b) << std::endl;
}
if constexpr ( can_invoke( subtract, a, b ) {
std::cout << "result of subtract: " << subtract(a, b) << std::endl;
}
}
这是c++14;在c++11中它更尴尬,在c++17更优雅,因为他们已经有一个可以调用类型特征(处理更多的角落案例;但是,它还希望你调用add
与std::invoke
)。
在c++17我有点像这个伎俩:
template<class F>
constexpr auto invoke_test( F&& ) {
return [](auto&&...args) ->
can_invoke_t<F, decltype(args)...>
{ return {}; };
}
template <typename A, typename B>
void foo(A a, B b) {
if constexpr ( invoke_test( add )( a, b ) ) {
std::cout << "result of add: " << add(a, b) << std::endl;
}
if constexpr ( invoke_test( subtract )( a, b ) {
std::cout << "result of subtract: " << subtract(a, b) << std::endl;
}
}
其中invoke_test
接受一个可调用的,并返回一个可调用的,其唯一的工作是回答“使用你传递给我的args调用原始的callable”。
答案 1 :(得分:3)
您可以将SFINAE放入返回类型,让函数重载告诉您是否可以进行调用。辅助函数can_be_called
可以实现如下:
#include <type_traits>
template<class Func, class... Args>
constexpr auto
can_be_called(Func&& func, Args&&... args)
-> decltype(
(std::forward<Func>(func)(std::forward<Args>(args)...)
, bool{}))
{ return true; }
struct Dummy {
template<class T> constexpr Dummy(T&&) {}
};
template<class... Args>
constexpr bool
can_be_called(Dummy, Args&&...) { return false; }
// test
#include <iostream>
void foo(int, int) {}
struct A{};
int main() {
if constexpr( can_be_called(foo, 1, 2) ) {
std::cout << "OK\n";
}
if constexpr ( !can_be_called(foo, A{}, 2) ) {
std::cout << "NO\n";
}
}