digitalmars.D.learn - Method-call based on template argument
I'm trying to do the following: module myModule; int calculate(T)(int a, int b) if(T == "add") { return a + b; } int calculate(T)(int a, int b) if(T == "subtract) { return a - b; } But when I try to run the following code, I get "template myModule.calculate" does not match any function template declaration": void main() { int a = 10; int b = 20; std.stdio.writeln(calculate!("add")(a, b)); std.stdio.writeln(calculate!("subtract")(a, b)); } Is there any way to check if the given template argument is "add" or "subtract"? I also tried: int calculate(string T)(int a, int b) if(T == "add") { return a + b; } int calculate(string T)(int a, int b) if(T == "subtract) { return a - b; } ... without any success (I'll get an instantiation error).
May 09 2012
On 05/09/2012 12:33 PM, nrgyzer wrote:void main() { int a = 10; int b = 20; std.stdio.writeln(calculate!("add")(a, b)); std.stdio.writeln(calculate!("subtract")(a, b)); }Below works ----------- import std.stdio; int calculate(string T)(int a, int b) if(T == "add") { return a + b; } int calculate(string T)(int a, int b) if(T == "subtract") { return a - b; } void main() { int a = 10; int b = 20; std.stdio.writeln(calculate!("add")(a, b)); std.stdio.writeln(calculate!("subtract")(a, b)); } Output ------ 30 -10
May 09 2012
Hm... yes - works. I simply rewrote my method-header and it just works, too... but thanks :)
May 09 2012