C ++显式char / short? [英] C++ explicit char/short?

查看:218
本文介绍了C ++显式char / short?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想传递一个字符到我的函数(fn)。我不想要ints和短裤被类型转换成它。所以我想我应该有值隐式转换成MyInt(这将只支持char)然后传递到fn。这应该工作bc IIRC只有一个打字允许当传递到函数(所以char-> MyInt是确定,而int-> char-> MyInt不应该)。

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).

然而,它似乎int和char工作,所以我想另一层间接(MyInt2)将修复它。现在他们都不能传递到fn ...有一种方法,我可以有chars传递,但不是int?

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
}


推荐答案

救援功能模板

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

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

如果有人尝试呼叫 fn char 参数之外的任何函数模板将被选为匹配,链接器将抱怨它找不到适当的专业化。

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.

这篇关于C ++显式char / short?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆