Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ explicit char/short?

Tags:

c++

I'd like to pass a char to my function (fn). I DO NOT want ints and shorts to be typecast into it. So i figure i should have the value be implicitly cast into MyInt (which will only support char) then pass into fn. This should work bc IIRC only one typcast is allowed when passing onto function (so char->MyInt is ok while int->char->MyInt shouldn't).

However it appears both int and char work so i figure another layer of indirection (MyInt2) would fix it. Now they both can not be passed into fn... Is there a way where i can have chars passed in but not int?

#include <cstdio>
struct MyInt2{
    int v;
    MyInt2(char vv){v=vv;}
    MyInt2(){}
};
struct MyInt{
    MyInt2 v;
    MyInt(MyInt2 vv){v=vv;}
};
void fn(MyInt a){
    printf("%d", a.v);
}
int main() {
    fn(1);       //should cause error
    fn((char)2); //should NOT cause error
}

1 Answers

Function templates to the rescue:

template<typename T> void fn(T t);

void fn (char a){
    printf("%c", a);
}

If someone attempts to call fn with anything other than a char argument the function template will be chosen as a match and the linker will complain that it cannot find the appropriate specialization.

like image 63
Jon Avatar answered Dec 08 '25 21:12

Jon