假设我在命名时有很多带有"*Pack"对应类的类.例如,如果我有一个Moo类,我有MooPack,如果我有Foo,我也有FooPack.
我想要一个c ++模板化函数,它从Foo返回一个FooPack
template <class X, class XPack>
XPack packify(X input){
...
}
Run Code Online (Sandbox Code Playgroud)
是否可以在不必指定模板参数的情况下执行此操作?目前,必须像下面这样做:
Moo moo;
MooPack mooppey = packify<Moo, MooPack>(moo);
Run Code Online (Sandbox Code Playgroud)
如果它只需要Moo模板参数,那个丑陋的模板规范位可能会消失,但除了使用#defines之外,这也不是最好的解决方案,但仍然没有这样做.
有办法,还是我必须等待c ++ 0x?
所以我有这种情况:
std::vector<Coord3D> thevector;
Run Code Online (Sandbox Code Playgroud)
其中Coord3D只是一个带有3个浮点数的简单结构:x,y和z.构造函数也只是简单地有x = 0; y = 0; z = 0; 等等
现在,假设我想将另一个向量的内容附加到向量中.
是否可以将向量的大小调整为thevector.size()+ theothervector.size(),而无需调用Coord3D()的构造函数?
原因是我想记忆其他向量的内容.在一些基准测试之后,用构造函数初始化内容结果需要一些时间.std :: loop fill也需要相当多的时间.
所以是的,有没有办法在绕过元素的构造函数的同时调整向量的大小?这会涉及狡猾的黑客行为吗?
假设我有一个非常复杂的缓冲区加扰函数,可以使用以下原型:
void do_something(char * thebuffer, int thelength);
Run Code Online (Sandbox Code Playgroud)
并且假设我需要让函数在std :: string上运行.但是std :: string.c_str()返回const char*,这是不可变的.
除了创建一个新的char*缓冲区,并将其传递给do_something之外,是否可以将do_something用于std :: string?
我的情况实际上是另一种方式(char*,int到std :: string和taking函数).
或者是绕过这个的唯一方法,就是去制作一个新的功能副本,它做同样的事情?(这真的不是很好的风格)
所以在C++中很多时候你需要创建一个"索引"类.例如:
class GameID{
public:
string name;
int regionid;
int gameid;
bool operator<(const GameID& rhs) const;
}
Run Code Online (Sandbox Code Playgroud)
现在,如果我们将GameID表示为pair<string, pair<int, int> >,那么运算符比较就是它.有没有其他方法来获得自动运算符比较而不必使用std :: pair <>?
所以我需要在ABRecordRef中添加一个推特账号.但是,似乎最快的方法是获取社交配置文件属性的多值引用,创建它的可变版本,查找它是否有twitter条目,如果它已经存在,则创建一个可变副本字典并用新的替换它.否则,使用twitter密钥和用户名创建一个新的字典条目.
它实际上变得非常冗长:
ABRecordRef person;
ABMultiValueRef oldsocials = ABRecordCopyValue(abperson, kABPersonSocialProfileProperty);
ABMutableMultiValueRef newsocials;
if(oldsocials){
newsocials = ABMultiValueCreateMutableCopy(oldsocials);
} else {
newsocials = ABMultiValueCreateMutable(kABMultiDictionaryPropertyType);
}
CFIndex socialsCount = ABMultiValueGetCount(socials);
bool foundtwitter = false;
for (int k=0 ; k<socialsCount ; k++) {
CFDictionaryRef socialValue = (CFDictionaryRef)ABMultiValueCopyValueAtIndex(socials, k);
if(socialValue){
if(CFStringCompare( (CFStringRef)CFDictionaryGetValue(socialValue, kABPersonSocialProfileServiceKey), kABPersonSocialProfileServiceTwitter, 0)==kCFCompareEqualTo) {
CFMutableDictionaryRef tomutate = CFDictionaryCreateMutableCopy(socialValue);
CFDictionarySetValue(tomutate, kABPersonSocialProfileUsernameKey, toNS(thetwitter));
ABMultiValueReplaceValueAtIndex(socials, tomutate, k);
CFRelease(tomutate);
foundtwitter = true;
}
CFRelease(socialValue);
}
if(foundtwitter)
break;
}
if(!foundtwitter){
ABMultiValueAddValueAndLabel(newsocials, [NSDictionary dictionaryWithObjectsAndKeys:
(NSString *)kABPersonSocialProfileServiceTwitter, kABPersonSocialProfileServiceKey,
@"justinbieber", kABPersonSocialProfileUsernameKey,
nil], …Run Code Online (Sandbox Code Playgroud)