我想创建一个类似的函数:
template < typename Other, typename Func, typename T, typename ...Rest >
void visit( Other &&other, Func &&visitor )
{
// Wrap "visitor" and "other" with "std::forward" calls
visitor( make_object<T>(other) );
visit<Other, Func, Rest...>( other, visitor );
}
问题是“Func”可能不支持列表中的所有类型,那么编译器将在第一个错误的类型处崩溃。我不想要那样;我希望它执行一些默认操作(对于我的情况,什么也不执行)。
template < typename Other, typename Func, typename T, typename ...Rest >
void visit( Other &&other, Func &&visitor )
{
// Wrap "visitor" and "other" with "std::forward" calls
if ( Func-can-support-T-either-directly-or-by-converting-it )
visitor( make_object<T>(other) );
else
; // might be a throw or a logging instead
visit<Other, Func, Rest...>( other, visitor );
}
我想我可以制作 2 个重载辅助函数,一个基于兼容性测试采用 std::true_type
,另一个采用 std::false_type
。但如何创建测试呢?
(建议更好的标题和/或附加标签。)
最佳答案
与计算中的所有问题一样,您只需要简单的间接级别即可:)
这是一个简单的 apply
函数,当事情没有按照您希望的那样工作时,它有一个默认实现。
template <typename Func>
void apply(Func&& f, ...) { std::cout << "default\n"; }
template <typename Func, typename T>
auto apply(Func&& f, T&& t) -> decltype(f(std::forward<T>(t))) {
return f(std::forward<T>(t));
}
我们可以很容易地运用它:
struct Foo {};
struct Bar {};
struct F {
void operator()(Foo) { std::cout << "Foo\n"; }
void operator()(Bar) { std::cout << "Bar\n"; }
};
int main() {
F f;
Foo foo;
Bar bar;
int i;
apply(f, foo);
apply(f, bar);
apply(f, i);
}
Ideone 给出 the following output :
Foo
Bar
default
正如预期的那样。
关于c++ - 是否可以使函数模板对不适当的类型而不是错误执行默认操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10257476/