c++ - 使用类模板参数推导制作静态接口
问题描述
我想创建一些宏来为模板化参数传递、存储等创建静态接口。我正在使用类模板参数推导,但我碰壁了。
#include <iostream>
template <typename Type>
struct Person
{
Type &object;
Person(Type &object) : object(object) {}
void walk(unsigned steps)
{
object.walk(steps);
}
void talk(const std::string &words)
{
object.talk(words);
}
};
struct MySelf
{
void walk(unsigned steps)
{
std::cout << "walking: " << steps << std::endl;
}
void talk(const std::string &words) const
{
std::cout << "talking: " << words << std::endl;
}
};
template <typename Type>
void testNConst(Person<Type> object)
{
object.walk(50);
object.talk("testing");
}
template <typename Type>
void testConst(Person<const Type> object)
{
object.talk("testing");
}
int main()
{
MySelf myself;
testNConst(Person{myself}); // compiles
testNConst(myself); // does not compile
testConst(myself); // does not compile
return 0;
}
输出:
../../../../src/py.com.personal/other/hanaTest/main.cpp:53:5: error: no matching function for call to 'testNConst'
testNConst(myself); // does not compile
^~~~~~~~~~
../../../../src/py.com.personal/other/hanaTest/main.cpp:35:6: note: candidate template ignored: could not match 'Person<type-parameter-0-0>' against 'MySelf'
void testNConst(Person<Type> object)
^
../../../../src/py.com.personal/other/hanaTest/main.cpp:54:5: error: no matching function for call to 'testConst'
testConst(myself); // does not compile
^~~~~~~~~
../../../../src/py.com.personal/other/hanaTest/main.cpp:42:6: note: candidate template ignored: could not match 'Person<const type-parameter-0-0>' against 'MySelf'
void testConst(Person<const Type> object)
^
2 errors generated.
有任何想法吗?
解决方案
类模板参数推导仅适用于创建对象(变量声明等)。
它根本不适用于函数参数或函数返回类型。您不能调用testNConst(myself)
,因为myself
它不适Person<T>
用于某些T
- 正常的函数扣除规则适用。
简而言之:
template <typename T> struct X { X(T ); };
X x = 42; // ok, ctad here
template <typename T>
void foo(X<T> );
foo(42); // error, ctad doesn't apply here
X bar() { return 42; } // error, ctad doesn't apply here either
推荐阅读
- c - DLL 构建和链接良好,但仍然获得 lnk2019 用于 dll 中定义的结构和函数(C 语言)
- java - 更新了在 java 中为 Eclipse IDLE 修复 textIO 的方法
- python - 代码在 Jupyter 中运行良好,但从未在终端中完成执行
- javascript - 带有 html 移动标题的导航抽屉
- ios - 是否可以根据其 FirebaseAuthentication ID 阻止设备访问应用程序?
- javascript - React 需要处理一些 if 条件
- apache-kafka - kafka 和 schema 注册表如何共享 KafkaProperties?(提供了“basic.auth.user.info”,但不是已知配置。)
- spring - @WebMvcTest vs @ContextConfiguration when testing WebSocket controllers
- apache - htaccess – FALSE If statement still runs
- json - How to write a sentence into JSON file in Qt not necessarily in JSON format?