我知道使用结构为返回类型重载的把戏:重载函数
struct function {
operator typeA() { return overloadForTypeA(); }
operator typeB() { return overloadForTypeB(); }
}
问题是,这种禁止参数和参数类型的重载。所以我一直在试图扩展使用模板这个概念:
struct function {
//template on the constructor so types are inffered from arguments
template<typename... Args>
funct(Args... arguments) { myArguments = arguments; }
//intermediate storeage of arguments, problem is the template doesn't extend to here
Args myArguments;
//overloads for return type int
int overloadForInt(char* chr) { return 20; }
int overloadForInt(int i) { return 4; }
//overloads for return type char
char overloadForChar(char* chr) { return 'c'; }
char overloadForChar(int i) { return 'i'; }
//implcit cast operators to archive return type overloading
operator int() { return overloadForInt(myArguments...); } //if myArguments doesn't match any overload of overloadForInt compile error should happen
operator char() { return overloadForChar(myArguments...); }
}
正如你看到的,我跑成的模板没有延伸到stuct休息的问题。有没有办法在整个结构体上扩展构造函数模板来解决这个特殊问题?还是有另一种方法来归档返回类型可重写,同时保持参数和参数类型重载?
请问您能解释一下您的意思吗?请禁用参数和参数类型重载? – linuxfever
使这个类本身成为一个模板,它需要'Args ...'(或任何你想要的名字)。 – 0x499602D2
通过“禁用参数...”我的意思是你不能传入任何参数,因为隐式转换不会带任何参数。另外,我不能将结构本身作为模板,因为参数的类型不会从构造函数中获取,所以不是“函数(参数)”,而是“函数<参数类型>(参数)” 。这破坏了与普通函数具有相同语法的目的。 (然后最好只使用一个虚拟指针) –