66

如何避免对非构造函数进行隐式强制转换?
我有一个将整数作为参数的函数,
但该函数也将采用字符、布尔值和长整数。
我相信它通过隐式转换它们来做到这一点。
我怎样才能避免这种情况,使函数只接受匹配类型的参数,否则将拒绝编译?
有一个关键字“explicit”,但它不适用于非构造函数。:\
我该怎么办?

以下程序编译,虽然我不希望它:

#include <cstdlib>

//the function signature requires an int
void function(int i);

int main(){

    int i{5};
    function(i); //<- this is acceptable

    char c{'a'};
    function(c); //<- I would NOT like this to compile

    return EXIT_SUCCESS;
}

void function(int i){return;}

*请务必指出任何对术语和假设的滥用

4

8 回答 8

77

定义匹配所有其他类型的函数模板:

void function(int); // this will be selected for int only

template <class T>
void function(T) = delete; // C++11 

这是因为具有直接匹配的非模板函数总是首先被考虑。然后考虑直接匹配的功能模板 - 所以永远function<int>不会使用。但是对于其他任何东西,比如 char,function<char>将被使用 - 这会给你的编译错误:

void function(int) {}

template <class T>
void function(T) = delete; // C++11 


int main() {
   function(1);
   function(char(1)); // line 12
} 

错误:

prog.cpp: In function 'int main()':
prog.cpp:4:6: error: deleted function 'void function(T) [with T = char]'
prog.cpp:12:20: error: used here

这是 C++03 方式:

// because this ugly code will give you compilation error for all other types
class DeleteOverload
{
private:
    DeleteOverload(void*);
};


template <class T>
void function(T a, DeleteOverload = 0);

void function(int a)
{}
于 2012-10-13T22:26:36.383 回答
25

您不能直接使用,因为 achar会自动提升为int.

不过,您可以使用一个技巧:创建一个以 achar作为参数的函数并且不实现它。它会编译,但你会得到一个链接器错误:

void function(int i) 
{
}
void function(char i);
//or, in C++11
void function(char i) = delete;

使用参数调用函数char将破坏构建。

http://ideone.com/2SRdM

术语:非构造函数?你的意思是一个不是构造函数的函数吗?

于 2012-10-13T22:22:39.633 回答
16

8 年后(PRE-C++20,见编辑):

如果您不介意模板函数(您可能会介意),最现代的解决方案是使用带有std::enable_ifand的模板函数std::is_same

即:

// Where we want to only take int
template <class T, std::enable_if_t<std::is_same_v<T,int>,bool> = false>
void func(T x) {
    
}

编辑 (c++20)

我最近切换到 c++20,我相信有更好的方法。如果您的团队或您不使用 c++20,或者不熟悉新概念库,请不要使用它。这要好得多,并且是新 c++20 标准中概述的预期方法,以及新功能的作者(阅读 Bjarne Stroustrup在这里写的论文。

template <class T>
    requires std::same_as(T,int)
void func(T x) {
    //...
}

小编辑(概念的不同模式)

以下是一个更好的方法,因为它解释了你的理由,有一个明确的 int。如果您经常这样做,并且想要一个好的模式,我会执行以下操作:

template <class T>
concept explicit_int = std::same_as<T,int>;

template <explicit_int T>
void func(T x) {

}

小编辑2(我保证的最后一个)

也是实现这种可能性的一种方法:

template <class T>
concept explicit_int = std::same_as<T,int>;

void func(explicit_int auto x) {

}
于 2021-04-08T13:53:01.020 回答
8

function这是一个通用解决方案,如果使用除 int 之外的任何内容调用,则会在编译时导致错误

template <typename T>
struct is_int { static const bool value = false; };

template <>
struct is_int<int> { static const bool value = true; };


template <typename T>
void function(T i) {
  static_assert(is_int<T>::value, "argument is not int");
  return;
}

int main() {
  int i = 5;
  char c = 'a';

  function(i);
  //function(c);

  return 0;
}

它的工作原理是允许参数的任何类型起作用,但is_int用作类型级别的谓词。的泛型实现is_int具有 false 值,但 int 类型的显式特化具有 true 值,因此静态断言保证参数具有精确的类型,int否则会出现编译错误。

于 2012-10-13T22:37:16.867 回答
2

对于 C++14(我相信 C++11),您也可以通过重载右值引用来禁用复制构造函数:

示例:假设您有一个基Binding<C>类,CConstraint类或继承类在哪里。假设您Binding<C>在向量中按值存储,并且传递对绑定的引用,并且希望确保不会导致隐式复制。

您可以通过删除func(Binding<C>&& x)(根据 PiotrNycz 的示例)来执行右值引用特定情况。

片段:

template<typename T>
void overload_info(const T& x) {
  cout << "overload: " << "const " << name_trait<T>::name() << "&" << endl;
}

template<typename T>
void overload_info(T&& x) {
  cout << "overload: " << name_trait<T>::name() << "&&" << endl;
}

template<typename T>
void disable_implicit_copy(T&& x) = delete;

template<typename T>
void disable_implicit_copy(const T& x) {
  cout << "[valid] ";
  overload_info<T>(x);
}

...

int main() {
  Constraint c;
  LinearConstraint lc(1);

  Binding<Constraint> bc(&c, {});
  Binding<LinearConstraint> blc(&lc, {});

  CALL(overload_info<Binding<Constraint>>(bc));
  CALL(overload_info<Binding<LinearConstraint>>(blc));

  CALL(overload_info<Binding<Constraint>>(blc));

  CALL(disable_implicit_copy<Binding<Constraint>>(bc));
  // // Causes desired error
  // CALL(disable_implicit_copy<Binding<Constraint>>(blc));
}

输出:

>>> overload_info(bc)
overload: T&&

>>> overload_info<Binding<Constraint>>(bc)
overload: const Binding<Constraint>&

>>> overload_info<Binding<LinearConstraint>>(blc)
overload: const Binding<LinearConstraint>&

>>> overload_info<Binding<Constraint>>(blc)
implicit copy: Binding<LinearConstraint>  ->  Binding<Constraint>
overload: Binding<Constraint>&&

>>> disable_implicit_copy<Binding<Constraint>>(bc)
[valid] overload: const Binding<Constraint>&

错误(带有clang-3.9in bazel,当违规行未注释时):

cpp_quick/prevent_implicit_conversion.cc:116:8: error: call to deleted function 'disable_implicit_copy'
  CALL(disable_implicit_copy<Binding<Constraint>>(blc));
       ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

完整源代码:prevent_implicit_conversion.cc

于 2017-04-17T19:28:47.237 回答
1

也许您可以使用结构将第二个函数设为私有:

#include <cstdlib>

struct NoCast {
    static void function(int i);
  private:
    static void function(char c);
};

int main(){

    int i(5);
    NoCast::function(i); //<- this is acceptable

    char c('a');
    NoCast::function(c); //<- Error

    return EXIT_SUCCESS;
}

void NoCast::function(int i){return;}

这不会编译:

prog.cpp: In function ‘int main()’:
prog.cpp:7: error: ‘static void NoCast::function(char)’ is private
prog.cpp:16: error: within this context
于 2012-10-13T22:32:07.467 回答
1

好吧,我打算用下面的代码来回答这个问题,但即使它适用于 Visual C++,在产生所需编译错误的意义上,MinGW g++ 4.7.1 接受它,并调用右值引用构造函数!

我认为这一定是一个编译器错误,但我可能是错的,所以——有人吗?

无论如何,这是代码,它可能会成为符合标准的解决方案(或者,这可能是我的想法!):

#include <iostream>
#include <utility>      // std::is_same, std::enable_if
using namespace std;

template< class Type >
struct Boxed
{
    Type value;

    template< class Arg >
    Boxed(
        Arg const& v,
        typename enable_if< is_same< Type, Arg >::value, Arg >::type* = 0
        )
        : value( v )
    {
        wcout << "Generic!" << endl;
    }

    Boxed( Type&& v ): value( move( v ) )
    {
        wcout << "Rvalue!" << endl;
    }
};

void function( Boxed< int > v ) {}

int main()
{
    int i = 5;
    function( i );  //<- this is acceptable

    char c = 'a';
    function( c );  //<- I would NOT like this to compile
}
于 2012-10-13T23:09:53.180 回答
0

我首先尝试了 PiotrNycz 的方法(对于 C++03,我被迫将其用于项目),然后我尝试找到一种更通用的方法并提出了这个ForcedType<T>模板类。

template <typename T>
struct ForcedType {
    ForcedType(T v): m_v(v) {}
    operator T&() { return m_v; }
    operator const T&() const { return m_v; }

private:
    template <typename T2>
    ForcedType(T2);

    T m_v;
};

template <typename T>
struct ForcedType<const T&> {
    ForcedType(const T& v): m_v(v) {}
    operator const T&() const { return m_v; }

private:
    template <typename T2>
    ForcedType(const T2&);

    const T& m_v;
};

template <typename T>
struct ForcedType<T&> {
    ForcedType(T& v): m_v(v) {}
    operator T&() { return m_v; }
    operator const T&() const { return m_v; }

private:
    template <typename T2>
    ForcedType(T2&);

    T& m_v;
};

如果我没记错的话,这三个专业应该涵盖所有常见的用例。我不确定是否真的需要专门针对右值引用(在 C++11 及更高版本上)或按值的一个就足够了。

如果一个函数有 3 个参数,其第 3 个参数不允许隐式转换,可以这样使用它:

function(ParamType1 param1, ParamType2 param2, ForcedType<ParamType3> param3);
于 2018-02-23T10:11:06.233 回答