C++ 具有特定参数的特定构造函数的类型声明
我有这个结构:C++ 具有特定参数的特定构造函数的类型声明,c++,c++11,C++,C++11,我有这个结构: struct A { A(int a, bool b):a(a), b(b) {}; int a; bool b; } 我可以用特定的参数为特定的构造函数调用声明一个类型声明吗 我是说,像这样的: typedef A(2, false) A_2_false; 所以我可以这样使用它: const A a_func() { return A_2_false; }; 它提醒std::bind在哪里调用函数,可以预先设置一些变量,而不是std::place
struct A {
A(int a, bool b):a(a), b(b) {};
int a;
bool b;
}
我可以用特定的参数为特定的构造函数调用声明一个类型声明吗
我是说,像这样的:
typedef A(2, false) A_2_false;
所以我可以这样使用它:
const A a_func() { return A_2_false; };
- 它提醒
在哪里调用函数,可以预先设置一些变量,而不是std::bind
std::place\u holders
- 我曾尝试使用
,但没有任何运气std::integral_常量
- 我不想使用
#define
typedef std::function CbFunc
简单用户应使用
CbFunc
并返回const A
。
我想让事情变得更简单,因此用户回调函数可以是:
const A userCbFunc() {
...
...
// Good thing happend
return A_2_false;
...
...
// Bad thing happend
return A(99, true);
}
我想使Good things appeated
返回类型更加简化,因此它将是A_2_false
而不是A(2,false)
然后,当函数返回时,我使用struct成员。使用lambda函数怎么样
auto A_2_false = []() { return A(2, false); };
然后使用
A myA = A_2_false();
a:
#包括
结构A{
A(int A,bool b):A(A),b(b){};
INTA;
布尔b;
};
自动设置为默认值=[]
{
返回A(2,假);
};
A A_func()
{
返回make_A_default();
}
int main()
{
自动a=a_func();
a、 a=5;
}
仅一个普通函数就可以做到这一点:
A A_2_false() { return A(2, false); }
用法:
A a_func()
{
return A_2_false();
}
尽管这在形式上需要几份副本,但所有副本都可以省略副本,因此此代码可以像原始代码一样有效地翻译。C++17甚至强制执行此副本省略
如果从A
的设计角度来看有意义,您还可以将A_2_false
设置为A
的静态成员函数:
struct A
{
static A two_false() { return A(2, false); }
// ...
};
A a_func()
{
return A::two_false();
}
这有时被称为“命名构造函数”。一种简单的方法是复制:
const A A_2_false(2, false); // a global, reusable instance
A a_func() {
return A_2_false;
};
试试这个
struct A {
A(int a=2, bool b=true):a(a), b(b) {};
int a;
bool b;
}
模板可能会有所帮助
#include <iostream>
#include <string>
template <int I, bool B>
struct A {
int i = I;
bool b = B;
static const A construct() { return {I, B}; }
};
int main()
{
using Type = A<2, false>;
std::cout << Type::construct().i << std::endl;
std::cout << Type::construct().b << std::endl;
return 0;
}
#包括
#包括
样板
结构A{
int i=i;
布尔b=b;
静态常量A构造(){return{I,B};}
};
int main()
{
使用类型=A;
std::cout Btw:Top-level const在返回值上没有多大意义,我想有些编译器甚至警告过它。你想实现什么?也许是你想要的?另一个选项可能是。
#include <iostream>
#include <string>
template <int I, bool B>
struct A {
int i = I;
bool b = B;
static const A construct() { return {I, B}; }
};
int main()
{
using Type = A<2, false>;
std::cout << Type::construct().i << std::endl;
std::cout << Type::construct().b << std::endl;
return 0;
}