4

考虑代码:

#include <type_traits>
#include <iostream>

struct test1 {
    void Invoke() {};
};

struct test2 {
    template<typename> void Invoke() {};
};


enum class InvokableKind {
    NOT_INVOKABLE,
    INVOKABLE_FUNCTION,
    INVOKABLE_FUNCTION_TEMPLATE
};

template<typename Functor, class Enable = void>
struct get_invokable_kind {
    const static InvokableKind value = InvokableKind::NOT_INVOKABLE;
};

template<typename Functor>
struct get_invokable_kind<
  Functor,
  decltype(Functor().Invoke())
  >
{
    const static InvokableKind value = InvokableKind::INVOKABLE_FUNCTION;
};

template<typename Functor>
struct get_invokable_kind<
  Functor,
  decltype(Functor().Invoke<void>())
  >
{
    const static InvokableKind value = InvokableKind::INVOKABLE_FUNCTION_TEMPLATE;
};


int main() {
    using namespace std;

    cout << (get_invokable_kind<test1>::value == InvokableKind::INVOKABLE_FUNCTION) << endl;
    cout << (get_invokable_kind<test2>::value == InvokableKind::INVOKABLE_FUNCTION_TEMPLATE) << endl;

}

我要做的是创建一个元函数来测试“可调用性”的特定定义。现在我在 GCC 4.5.3 上遇到了这个编译错误:

prog.cpp:37:3:错误:模板参数 2 无效

这是什么意思?为什么我可以专精decltype(Functor().Invoke()),却不能专精decltype(Functor().Invoke<void>())

4

1 回答 1

6

template由于解析歧义,您需要对其进行限定:

 decltype(Functor().template Invoke<void>())
                    ^^^^^^^^

相关:我必须在哪里以及为什么要放置“模板”和“类型名称”关键字?

另外,考虑使用std::declval而不是Functor()构造函数。

于 2012-11-12T13:53:06.973 回答