const 指针作为 std::bind 参数

per*_*cia 1 c++ stdbind

以下代码

#include <functional>
#include <iostream>

using namespace std;

struct TestStruct {
  int c;
};

int f(int a, int b, const TestStruct **t) { return a + b + (*t)->c; }

void main() {

  TestStruct *t;
  bind(&f, 1, 2, &t)();
}
Run Code Online (Sandbox Code Playgroud)

报告这个错误

error C2893: Failed to specialize function template 'unknown-type std::invoke(_Callable &&,_Types &&...)'
note: With the following template arguments:
note: '_Callable=int (__cdecl *&)(int,int,const TestStruct **)'
note: '_Types={int &, int &, TestStruct **&}'
Run Code Online (Sandbox Code Playgroud)

似乎问题在于const TestStruct**参数的常量性。但是,无论是 withconst TestStruct *还是 with都没有问题TestStruct**。为什么 ?

Fra*_*ank 5

您的问题不是来自 bind 本身,而是来自强制T**转换T const**为非法的简单事实。

有关原因的解释,请参见http://c-faq.com/ansi/constmismatch.html