c++ - 是否可以使函数模板对不适当的类型而不是错误执行默认操作?

标签 c++ c++11

我想创建一个类似的函数:

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/

相关文章:

c++ - C5002 1204 自动矢量化程序原因代码是什么意思?

c++ - 类中字符串指针的编译错误

c++ - _cvLoadImage undefined symbol 链接问题

c++ - 为什么在成员函数上为 *this 指定左值引用与不指定任何内容不同?

c++ - 这是 clang c++11 std::regex_match 的一个特性还是一个错误?

c++ - 更现代的循环 C++ 数组的方式

c++ - Visual Studio 2012/2013 语法突出显示错误

c++ - 猜测运行时函数的返回类型

c++ - 如何通过非类型参数选择特化

c++ - 使用模板将多个 vector (函数的结果)组合成一个