显式 void 指针作为函数参数

Explicit void pointer as function parameter

我有一个功能:

int foo(void * ptr)
{
   // ...
}

我能否在 C++11/14 中从语法上(不使用编译器警告等)禁止向那里传递 void * 本身以外的指针?

例如,现在可以这样调用:

foo(new int(42));

我需要禁用它。

惯用的方法是创建一个新类型来表示 void* 以避免您描述的问题。许多 C++ 良好实践的拥护者建议创建类型以避免对应该传入的内容产生任何疑问,并避免编译器让您这样做。

class MyVoid
{
//... implement in a way that makes your life easy to do whatever you are trying to do with your void* stuff
};

int foo(MyVoid ptr)
{
   // ...
}

如果你想要精确的类型匹配,你可以使用std::enable_if with std::is_same

#include <iostream>
#include <type_traits>

template <typename T,
          typename = typename std::enable_if_t<std::is_same<T, void*>::value>>
int foo(T value)
{
    return 5;
}

int main()
{
    // return foo(new int(42)); // error: no matching function for call to 'foo(int*)'
    return foo((void*)(new int(42)));
}

我想还有很多其他的方法。

使用模板函数很简单(它也适用于 C++98)

template <typename X>
int foo (X * ptr);

int foo (void * ptr)
 { return 1; }

int main()
 {
   int  i;
   void * vp = &i;

   foo(vp);  // OK
   foo(&i);  // linker error

   return 0;
 }

正如 frymode 指出的那样,前面的解决方案给出了链接器错误,而不是编译器错误,最好得到编译器错误。

使用 delete(来自 C++11),我们可以通过使用以下代码得到编译器错误:

template <typename X>
int foo (X ptr) = delete;

希望对您有所帮助。

你可以利用pedantic pointer idiom。您的代码应如下所示。它利用了这样一个事实,即在更高的间接级别上没有隐式转换:

[live]

int foo_impl(void * ptr, void **)
{
   return 0;
}

template <typename T>  
void foo(T* t)  
{  
  foo_impl(t, &t);  
}  

int main()
{
    void* pv;
    foo(pv);
    //foo(new int(2)); // error: error: invalid conversion from 'int**' to 'void**'
}

您可以将函数转换为模板,然后使用 type_traits:

中的 static_assertstd::is_void
template<typename T>
int foo(T *ptr) {
    static_assert(std::is_void<T>::value, "!");
   // ....
}

否则,您可以在 return 类型上使用 std::enable_if_t

template<typename T>
std::enable_if_t<std::is_void<T>::value, int>
foo(T *ptr) {
    // ....
    return 0;
}

等等,其他有趣的解决方案已经被其他用户提出并给出了答案。

这是一个最小的工作示例:

#include<type_traits>

template<typename T>
int foo(T *ptr) {
    static_assert(std::is_void<T>::value, "!");
    // ....
    return 0;
}

int main() {
    int i = 42;
    void *p = &i;
    foo(p);
    // foo(&i); // compile error
}

您不需要 C++11 来确保编译时错误:

template<class> struct check_void;

template<> struct check_void<void> { typedef void type; };

template<class T> typename check_void<T>::type *foo(T *ptr) { return ptr; }
 
int main()
{
    foo(static_cast<void *>(0));  // success
    foo(static_cast<int *>(0));  // failure
}