我偶然发现了一个在处理模板时遇到麻烦的小问题.这是一个例子:
template<class _returnType, _returnType (*_function)()>
_returnType aliasGetter() { return _function(); }
int getCoolNumber() { return 42; }
int main()
{
std::cout << aliasGetter<int, &getCoolNumber>(); //42
}
Run Code Online (Sandbox Code Playgroud)
这段代码有效(http://cpp.sh/如果你想尝试一下),但是因为我给一个函数指针作为模板参数我不需要_returnType,它就在函数签名中,问题是,没有无论我怎么努力,我都找不到摆脱这个额外模板参数的方法.
如何aliasGetter只使用一个模板参数(指向getter的别名指针)?如果那不可能,为什么不呢?
考虑以下示例程序:
#include <iostream>
using namespace std;
struct t
{
~t() {cout << "destroyed\n"; }
};
int main()
{
cout << "test\n";
t(), cout << "doing stuff\n";
cout << "end\n";
}
Run Code Online (Sandbox Code Playgroud)
我从GCC 4.9.2获得的输出是:
test
doing stuff
destroyed
end
Run Code Online (Sandbox Code Playgroud)
cpp.sh链接:http://cpp.sh/3cvm
但是根据关于逗号运算符的cppreference:
在逗号表达式E1,E2中,评估表达式E1,丢弃其结果,并且在评估表达式E2开始之前完成其副作用
我希望~t()以前能打电话给我cout << "doing stuff"
这是标准行为吗?如果是这样,标准中的定义在哪里?
c++ object-lifetime comma-operator language-lawyer temporary-objects
这是我想要实现的运行示例:
#include <iostream>
#include <string>
#include <typeinfo>
template <class T>
struct print
{
static void function( T thing)
{
std::cout << thing << std::endl;
}
};
template <class T>
struct printMore
{
static void function( T thing )
{
std::cout << thing << " and more" << std::endl;
}
};
struct dynamicBase
{
const char* m_value;
size_t getType()
{
switch( *m_value )
{
case '0': //the string is going to be a small script, the type returned is known during …Run Code Online (Sandbox Code Playgroud)