gpt4 book ai didi

c++ - 带有模板参数的 decltype

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:37:09 25 4
gpt4 key购买 nike

test1.cpp 编译,但 test2.cpp 不编译。两者之间的唯一区别是我在 test1.cpp 中的类声明中定义了 Handle::add_it,但在 test2.cpp 中定义了类声明.

test1.cpp:g++ test1.cpp -o test1 -std=c++11

#include <iostream>

template<typename B>
class Handle
{
public:
decltype(B.operator(int)) add_it(int x)
{
return b(x);
}

B b;
};

struct Add1
{
int operator()(int x)
{
return x + 1;
}
};

int main()
{
Handle<Add1> h;
std::cout << h.add_it(5) << std::endl;
}

test2.cpp:g++ test2.cpp -o test2 -std=c++11

#include <iostream>

template<typename B>
class Handle
{
public:
decltype(B.operator(int)) add_it(int x);

B b;
};

template<typename B>
decltype(B.operator(int)) Handle<B>::add_it(int x)
{
return b(x);
}

struct Add1
{
int operator()(int x)
{
return x + 1;
}
};

int main()
{
Handle<Add1> h;
std::cout << h.add_it(5) << std::endl;
}

错误

test2.cpp:13:11: error: expected primary-expression before ‘.’ token
decltype(B.operator(int))
^
test2.cpp:13:20: error: expected type-specifier before ‘(’ token
decltype(B.operator(int))
^
test2.cpp:13:21: error: expected primary-expression before ‘int’
decltype(B.operator(int))

最佳答案

您可以使用 std::declval 修改它:

template<typename B>
class Handle
{
public:
decltype(std::declval<B>()(int())) add_it(int x) {
return b(x);
}

B b;
};

Live Demo

或者在类的定义之外:

template<typename B>
class Handle {
public:
decltype(std::declval<B>()(int())) add_it(int x);
B b;
};

template<typename B>
decltype(std::declval<B>()(int())) Handle<B>::add_it(int x) {
return b(x);
}

Live Demo

关于c++ - 带有模板参数的 decltype,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34740248/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com