我的C++模板失败:非模板结构的显式专用化



我在 mac 上使用 clang 并拥有:

$cat my.cpp
#include<type_traits>
using namespace std;
template<int i>
struct place_holder{};
place_holder<1> _1;
place_holder<2> _2;
template<typename T>
struct is_placeholder:public integral_constant<int,0>{};
template<int i>
struct is_placeholder<place_holder<i> >:public integral_constant<int,i>{};
template<typename T>
int check(T&& t){
return is_placeholder<t>()::value;
}
int main(){
int i=check<_1>();
return 0;
}

最后一行编译失败:

my.cpp:13:27: error: template argument for template type parameter must be a type
return is_placeholder<t>()::value;
^
my.cpp:7:19: note: template parameter is declared here
template<typename T>
^
my.cpp:16:11: error: no matching function for call to 'check'
int i=check<_1>();
^~~~~~~~~
my.cpp:12:5: note: candidate function template not viable: requires single argument 't', but no arguments were
provided
int check(T&& t){
^
2 errors generated.

真的很奇怪,我的"结构is_placeholder"真的是一个模板,对吧?为什么说不是?

如何更正我的程序?谢谢!

似乎你有点混淆了类型和对象。

例如,您在尝试使用t实例化模板时犯了一个错误,该模板不是一种类型:

return is_placeholder<t>()::value;
^^^^^^
here

此外,您已将check定义为接受单个参数但在调用期间不提供任何参数的函数。

我建议你做下一个:

  1. 创建_1_2类型:

    using _1 = place_holder<1>;
    using _2 = place_holder<2>;
    
  2. 更改check函数,如下所示:

    template<typename T>
    auto check() {
    return is_placeholder<T>::value;
    }
    

然后用作:

auto i = check<_1>();

这是一个固定版本:WANDBOX

最新更新